// stores/dataStore.js
import { defineStore } from 'pinia'
import { ref, type Ref, reactive, computed } from 'vue'
import store from '@/store'
import { historyDataStore } from './historyStore'
import { sumValues } from '../../utils/common'
import Decimal from 'decimal.js'
import dayjs from 'dayjs'
import { items, ArrayType } from '@renderer/api/quote/types'
import { ElMessage } from 'element-plus'

export const tableDataStore = defineStore('tableData', () => {
  // #region processorStore的引用
  // 创建 processorStore 的引用（非实例化）
  let processor: ReturnType<typeof historyDataStore>
  const initProcessor = () => {
    if (!processor) processor = historyDataStore() // ✅ 惰性实例化
  }
  // #endregion

  // #region 表单操作
  const isEditBoolendis = ref<boolean>(false)
  const isEditBoolenbuy = ref<boolean>(false)
  const discount = reactive({
    acceptor: '',
    matter: '',
    billAmount: '',
    points: '',
    open: 1
  })
  const buys = reactive({
    acceptor: '',
    matter: '',
    billAmount: '',
    points: '',
    open: 1
  })
  const clearForm = (type: string) => {
    if (type === 'discountForm') {
      discount.acceptor = ''
      discount.matter = ''
      discount.billAmount = ''
      discount.points = ''
      discount.open = 1
    } else {
      buys.acceptor = ''
      buys.matter = ''
      buys.billAmount = ''
      buys.points = ''
      buys.open = 1
    }
  }
  const getClickItem = (type: 'discountList' | 'buysList', index: number) => {
    if (currentItemIndex.value !== null && currentItemType.value !== type) {
      if (currentItemType.value === 'discountList') {
        isEditBoolendis.value = false
        clearForm('discountForm')
      } else {
        isEditBoolenbuy.value = false
        clearForm('buysForm')
      }
    }

    currentItemIndex.value = index
    currentItemType.value = type
    if (type === 'discountList') {
      isEditBoolendis.value = true
      discount.acceptor = discountList.value[index].acceptor
      discount.matter = discountList.value[index].matter
      discount.billAmount = discountList.value[index].billAmount
      discount.points = discountList.value[index].points
      discount.open = discountList.value[index].open
    } else {
      isEditBoolenbuy.value = true
      buys.acceptor = buysList.value[index].acceptor
      buys.billAmount = buysList.value[index].billAmount
      buys.points = buysList.value[index].points
      buys.open = buysList.value[index].open
    }
  }
  // #endregion

  // #region 表格内容的处理
  const discountList = ref<items[]>([])
  const buysList = ref<items[]>([])
  const discountTotal = reactive({
    serialNumber: '',
    matter: '',
    acceptor: '',
    billAmount: '',
    points: '',
    open: '',
    rebate: '',
    interestDeduction: ''
  })
  const buyTotal = reactive({
    serialNumber: '',
    matter: '',
    acceptor: '',
    billAmount: '',
    points: '',
    open: '',
    rebate: '',
    interestDeduction: ''
  })

  const total = reactive({
    acceptor: '',
    billAmount: '',
    points: '',
    open: '',
    rebate: '',
    interestDeduction: ''
  })
  // 重置total
  const resetTotal = () => {
    total.acceptor = ''
    total.billAmount = ''
    total.points = ''
    total.open = ''
    total.rebate = ''
    total.interestDeduction = ''
    buyTotal.billAmount = ''
    buyTotal.rebate = ''
    discountTotal.billAmount = ''
    discountTotal.interestDeduction = ''
  }
  // 1. 定义类型
  interface CalculateTotalsResult {
    billAmount: string
    interestDeduction?: string
    rebate?: string
  }
  const onTotal = async () => {
    await resetTotal()
    const hasDiscountItems = discountList.value.length > 0
    const hasBuysItems = buysList.value.length > 0

    // 1. 提取公共计算逻辑
    const calculateTotals = (list, keys): CalculateTotalsResult => {
      const { billAmount, ...rest } = sumValues(list)
      const result = { billAmount: new Decimal(billAmount || 0).toString() }
      keys.forEach((key) => {
        result[key] = new Decimal(rest[key] || 0).round().toString()
      })
      return result
    }

    // 2. 按场景重构逻辑
    if (hasDiscountItems && !hasBuysItems) {
      const discountData = calculateTotals(discountList.value, ['interestDeduction'])
      discountTotal.billAmount = discountData.billAmount
      discountTotal.interestDeduction = discountData.interestDeduction || '0'
      Object.assign(total, {
        acceptor: '合计',
        billAmount: discountData.billAmount,
        points: '贴息费',
        interestDeduction: discountData.interestDeduction
      })
    } else if (!hasDiscountItems && hasBuysItems) {
      const buysData = calculateTotals(buysList.value, ['rebate'])
      buyTotal.billAmount = buysData.billAmount
      buyTotal.rebate = buysData.rebate || '0'
      Object.assign(total, {
        acceptor: '合计',
        billAmount: buysData.billAmount,
        points: '返点',
        interestDeduction: buysData.rebate
      })
    } else if (hasDiscountItems && hasBuysItems) {
      const discountData = calculateTotals(discountList.value, ['interestDeduction'])
      const buysData = calculateTotals(buysList.value, ['rebate'])
      discountTotal.billAmount = discountData.billAmount
      discountTotal.interestDeduction = discountData.interestDeduction || '0'
      buyTotal.billAmount = buysData.billAmount
      buyTotal.rebate = buysData.rebate || '0'

      // 3. 票面差额计算
      const billAmountDiff = new Decimal(discountData.billAmount).sub(buysData.billAmount)
      if (billAmountDiff.eq(0)) {
        total.acceptor = ''
        total.billAmount = '已走平'
      } else {
        total.acceptor = '票面差额'
        total.billAmount = Math.abs(billAmountDiff.toNumber()).toString()
      }

      // 4. 贴息/返点差额计算
      const interestDiff = new Decimal(discountData.interestDeduction || 0).sub(
        buysData.rebate || 0
      )
      if (interestDiff.eq(0)) {
        total.points = ''
        total.interestDeduction = '已走平'
      } else {
        total.points = interestDiff.gte(0) ? '贴息费' : '返点'
        total.interestDeduction = Math.abs(interestDiff.round().toNumber()).toString()
      }
    }

    // 5. 统一处理负号 (修复原代码只替换第一个负号的BUG)
    total.billAmount = total.billAmount.replace('-', '')
    total.interestDeduction = total.interestDeduction.replace('-', '')
    total.rebate = total.rebate.replace('-', '')
  }

  // 当前选中的数据（记录来自哪个列表）
  const currentItemIndex = ref<number | null>(null)
  const currentItemType = ref<string | null>(null)

  // 独立添加方法
  const createAddItem =
    (listRef: Ref<items[]>) => (item: items, type: 'discountList' | 'buysList') => {
      const newItem = { ...item, serialNumber: listRef.value.length + 1 }
      listRef.value.push(newItem) // 直接使用 push
      if (type === 'discountList') {
        isEditBoolendis.value = false
        clearForm('discountForm')
      } else if (type === 'buysList') {
        isEditBoolenbuy.value = false
        clearForm('buyForm')
      }
      onTotal()
    }
  // 生成各列表的专用方法
  const addDiscountItem = createAddItem(discountList)
  const addBuysItem = createAddItem(buysList)
  // 提交函数（按类型调用）
  const doSubmit = (item: items, type: 'discountList' | 'buysList') => {
    if (type === 'discountList') addDiscountItem(item, type)
    else if (type === 'buysList') addBuysItem(item, type)
  }

  // 独立修改方法（强制索引校验）
  const updateItem = (listRef: Ref<items[]>) => (index: number, item: items) => {
    console.log('updateItem', index, item)

    // const updateItem = (listRef: Ref<items[]>, index: number, item: items) => {
    if (index < 0 || index >= listRef.value.length) {
      throw new Error(`索引 ${index} 越界，有效范围 [0, ${listRef.value.length - 1}]`)
    }

    const updatedList = [...listRef.value]
    updatedList[index] = {
      ...item,
      matter: listRef.value[index].matter, // 保留原事项
      serialNumber: listRef.value[index].serialNumber // 保留原序列号
    }
    listRef.value = updatedList
    onTotal()
  }

  // 生成各列表的专用方法
  const updateDiscountItem = updateItem(discountList)
  const updateBuysItem = updateItem(buysList)
  // 提交函数（按类型调用）
  const doUpdate = async (item: items, type: 'discountList' | 'buysList') => {
    console.log('doUpdate', item, type)
    console.log(currentItemIndex.value)
    if (currentItemIndex.value !== null) {
      if (currentItemIndex.value == null) {
        throw new Error('请先选择要修改的项')
      }
      if (type === 'discountList') {
        // item.matter = '贴现'
        isEditBoolendis.value = false
        await clearForm('discountForm')
        await updateDiscountItem(currentItemIndex.value, item)
        currentItemIndex.value = null
      } else if (type === 'buysList') {
        console.log('buy')
        // item.matter = '买票'
        isEditBoolenbuy.value = false
        await clearForm('buyForm')
        await updateBuysItem(currentItemIndex.value, item)
        currentItemIndex.value = null
      }
    }
  }

  const getLists = async (item: string) => {
    const hisObj = JSON.parse(item)
    discountList.value = hisObj.discount
    buysList.value = hisObj.buy
    await onTotal()
  }
  const clearLists = () => {
    discountList.value = []
    buysList.value = []
    isEditBoolendis.value = false
    isEditBoolenbuy.value = false
    buyTotal.billAmount = '0'
    discountTotal.billAmount = '0'
    clearForm('discountForm')
    clearForm('buyForm')
  }

  // 计算 specialNum
  const specialNum = computed(() => {
    try {
      // ✅ 优化1：提取长度变量减少响应式访问
      const discountLen = discountList.value.length
      const buysLen = buysList.value.length

      // ✅ 优化2：使用变量重写条件
      const conditionMet =
        (discountLen > 0 && buysLen === 0) || // 仅折扣券
        (buysLen > 0 && discountLen === 0) || // 仅购买项
        (discountLen > 0 &&
          buysLen > 0 &&
          Number(discountTotal.billAmount) > Number(buyTotal.billAmount)) // 混合且折扣账单更大

      // ✅ 优化3：简化条件分支 + 修复变量错误
      let billAmount: Decimal
      let interestDeduction: Decimal

      if (conditionMet) {
        if (discountLen > 0 && buysLen === 0) {
          // 场景A：纯折扣券
          billAmount = safeDecimal(discountTotal.billAmount)
          interestDeduction = safeDecimal(discountTotal.interestDeduction)
        } else if (buysLen > 0 && discountLen === 0) {
          // 场景B：纯购买项
          billAmount = safeDecimal(buyTotal.billAmount)
          interestDeduction = safeDecimal(buyTotal.rebate)
        } else {
          // ✅ 修复：原代码错误使用了 total → 改为 discountTotal
          billAmount = safeDecimal(total.billAmount)
          interestDeduction = safeDecimal(total.interestDeduction)
        }
      } else {
        // 条件不满足时归零
        billAmount = new Decimal(0)
        interestDeduction = new Decimal(0)
      }

      // 计算最终值（利息向上取整）
      return billAmount.sub(interestDeduction.ceil()).toNumber()
    } catch (error) {
      console.error('计算错误:', error)
      return 0
    }
  })

  // 安全数值转换（防御 NaN）
  const safeDecimal = (value: unknown): Decimal => {
    const num = Number(value) || 0
    return new Decimal(Number.isNaN(num) ? 0 : num)
  }

  const setItemsCheckedStatus = (type: ArrayType, isChecked: boolean) => {
    if (type === ArrayType.DISCOUNT || type === ArrayType.ALL) {
      // 修改discountList中所有元素的checked值
      discountList.value = discountList.value.map((item) => ({
        ...item,
        checked: isChecked
      }))
    }

    if (type === ArrayType.BUYS || type === ArrayType.ALL) {
      // 修改buysList中所有元素的checked值
      buysList.value = buysList.value.map((item) => ({
        ...item,
        checked: isChecked
      }))
    }
  }

  // #endregion

  // #region 功能栏操作
  const tableName = ref<string | null>(null)
  const tableId = ref<number | null>(null)

  const clear = () => {
    clearLists()
    initProcessor()
    processor.resetHistoryActive()
  }

  const deleteRows = () => {
    if (currentItemIndex.value != null) {
      // 更新合计
      onTotal()
      if (currentItemType.value === 'discountList') {
        discountList.value.splice(currentItemIndex.value, 1)
        discountList.value.forEach((item, i) => {
          item.serialNumber = i + 1
        })
        clearForm('discountForm')
        isEditBoolendis.value = false
      } else if (currentItemType.value === 'buysList') {
        buysList.value.splice(currentItemIndex.value, 1)
        buysList.value.forEach((item, i) => {
          item.serialNumber = i + 1
        })
        clearForm('buysForm')
        isEditBoolenbuy.value = false
      }
      currentItemIndex.value = null
    } else {
      ElMessage({
        message: '请先选择要删除的项',
        type: 'warning'
      })
    }
  }

  const deleteRowRight = (type: 'discount' | 'buys', items: items) => {
    const lists = type === 'discount' ? discountList : buysList
    // 找到要删除的行索引
    const index = lists.value.findIndex((item) => item.serialNumber === items.serialNumber)
    if (index !== -1) {
      // 删除行
      lists.value.splice(index, 1)

      // 重新编号
      lists.value.forEach((item, i) => {
        item.serialNumber = i + 1
      })

      // 更新合计
      onTotal()
      if (type === 'discount') {
        clearForm('discountForm')
        isEditBoolendis.value = false
      } else {
        clearForm('buysForm')
        isEditBoolenbuy.value = false
      }
      currentItemIndex.value = -1
    }
  }

  const deleteChooseRow = () => {
    discountList.value = discountList.value.filter((item) => item.checked === true)
    buysList.value = buysList.value.filter((item) => item.checked === true)

    // 重置序号
    discountList.value.forEach((item, index) => {
      item.serialNumber = index + 1
      item.checked = false
    })
    buysList.value.forEach((item, index) => {
      item.serialNumber = index + 1
      item.checked = false
    })

    // 修改后更新合计
    onTotal()
  }

  const saves = async () => {
    initProcessor()
    const data = {
      discount: discountList.value,
      buy: buysList.value
    }
    // value 改为 当前时间
    let value = dayjs().format('HH:mm')
    const buyAmount = new Decimal(buyTotal.billAmount || 0)
    const discountAmount = new Decimal(discountTotal.billAmount || 0)
    const billAmount = buyAmount.plus(discountAmount) // 保留两位小数
    value = value + '-' + billAmount
    const res = await processor.addHistory({
      text: JSON.stringify(data),
      name: value
    })
    if (res) {
      clearLists()
      processor.getHistoryList()
      processor.getFinishCount()
    }
  }

  const edits = async () => {
    console.log('edits')
    initProcessor()
    const historyActive = processor.getHistoryActive()
    if (historyActive < 0) {
      return false
    }
    const list = processor.getHistoryActiveItem()
    // value 改为 当前时间
    let value = dayjs().format('HH:mm')
    if (list.company_id != 0 && list.company_name != '' && list.company_id != null) {
      value = value + '-' + list.company_name
    } else {
      // 将 billAmount 转换为数字类型并相加
      // 使用 Decimal.js 进行精确的金额计算
      const buyAmount = new Decimal(buyTotal.billAmount || 0)
      const discountAmount = new Decimal(discountTotal.billAmount || 0)
      const billAmount = buyAmount.plus(discountAmount) // 保留两位小数

      value = value + '-' + billAmount
    }
    // value = value + '-' + list.company_name
    const data = {
      discount: discountList.value,
      buy: buysList.value
    }
    const res = await processor.updateHistory({
      id: list.id,
      text: JSON.stringify(data),
      name: value
    })

    if (res) {
      clearLists()
      processor.getHistoryList()
      processor.resetHistoryActive() // 重置历史记录
      return true
    } else {
      return false
    }
  }
  // #endregion

  // 用于通知组件关闭右键菜单的事件标志
  const closeContextMenuFlag = ref(false)

  // 处理点击空白处清空表单和关闭右键菜单
  const handleClickOutside = () => {
    // if (currentItemIndex.value != null) {
    //   currentItemIndex.value = null
    // }
    // isEditBoolendis.value = false
    // isEditBoolenbuy.value = false
    // clearForm('discountForm')
    // clearForm('buyForm')

    // 触发关闭右键菜单的标志
    closeContextMenuFlag.value = !closeContextMenuFlag.value
  }

  const isCompleteBoolean = ref<boolean>(true)
  const special = ref<boolean>(false)

  const handleComplete = () => {
    isCompleteBoolean.value = !isCompleteBoolean.value
    special.value = !special.value
  }

  const isBillingBoolean = ref<boolean>(true)
  const handleBilling = () => {
    isBillingBoolean.value = !isBillingBoolean.value
  }

  const isCaptureMode = ref<boolean>(false)
  const doisCaptureMode = () => {
    isCaptureMode.value = !isCaptureMode.value
  }
  return {
    isCompleteBoolean,
    isBillingBoolean,
    handleBilling,
    special,
    handleComplete,
    getLists,
    discountList,
    buysList,
    doSubmit,
    doUpdate,
    getClickItem,
    currentItemIndex,
    currentItemType,
    clear,
    clearLists,
    deleteRows,
    deleteRowRight,
    deleteChooseRow,
    saves,
    edits,
    tableName,
    tableId,
    total,
    discountTotal,
    buyTotal,
    clearForm,
    isEditBoolendis,
    isEditBoolenbuy,
    discount,
    buys,
    specialNum,
    closeContextMenuFlag, // 暴露关闭右键菜单的标志
    handleClickOutside,
    isCaptureMode,
    doisCaptureMode,
    setItemsCheckedStatus
  }
})

/** 在 setup 外使用 */
export function tableDataStoreHook() {
  return tableDataStore(store)
}
